// pages/specialApply/specialApply.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageType: 0,
    typeList: [],
    typeIndex: '',
    username: '',
    // sexList: ['男', '女'],
    auditList: ['年审', '月审'],
    // sexIndex: 0,
    auditIndex: 0,
    phonenum: '',
    communityList: [],
    communityIndex: '',
    isDisabled: false,
    disabled: false,
    address: '',
    rechargeList: [],
    rechargeIndex: 0,
    deposit: [],
    depositIndex: 0,
    cardnum: '',
    certificatesList: [],
    certificatesIndex: 0,
    upLoad: '/images/imageload.png',
    close: '/images/close1.png',
    tempFilePaths: [],
    all_url_arr: [],
    url_arr: [],
    areaInfo_name: [], //选中地区名称
    area_id_Info: [], //选中的地区id信息
    isUpload: false,
    id: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let pageType = options.type || 0;
    let title = "特殊水卡申请";
    let disabled = false;
    this.from = options.from; //1来自合伙人-水卡管理进入  2来自合伙人-加盟商-水卡管理
    if (pageType == 1) {
      title = "查看特殊水卡";
      disabled = true
    } else if (pageType == 2) {
      title = "特殊水卡编辑";
    }
    wx.setNavigationBarTitle({
      title,
    })
    this.setData({
      disabled,
      pageType,
      id: options.id
    })

    Promise.all([
      this.getVillage(),
      this.getDeposit(),
      this.getCardType(),
      this.getCredentialType(),
      this.getSpecialCardRechargeConfig(),
    ]).then(([communityList, deposit, typeList, certificatesList, rechargeList]) => {
      this.setData({
        communityList,
        deposit,
        typeList,
        certificatesList,
        rechargeList
      })
      if (this.data.pageType != 0) {
        this.getIngo(this.data.id);
      }
      console.log(communityList, deposit, typeList, certificatesList, rechargeList)
    }).catch(e => {
      console.log(e)
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.cascade = this.selectComponent("#cascade")
  },

  showCascade() {
    if (this.data.pageType !== 1) {
      this.cascade.selection(this.data.area_id_Info)
    }
  },

  cascadeComplete(e) {
    const detail = e.detail;
    this.setData({
      areaInfo_name: detail.names,
      area_id_Info: detail.ids
    })
  },



  fetch(url, errTxt, data) {
    return new Promise((resolve, reject) => {
      app.ajax({
        url,
        data,
        success: res => {
          if (res.data.code > 0) {
            resolve(res.data.data)
          } else {
            reject(res.data.message || errTxt)
          }
        },
        error: e => {
          reject("网络错误")
        }
      })
    })
  },

  //获取园区列表
  getVillage() {
    const data = {};
    if (this.from == 2) {
      data.get_type = 1;
    }
    return this.fetch("Partner/Village/getAllVillage", "获取园区列表失败", data)
  },

  //获取押金配置
  getDeposit() {
    return this.fetch("Common/Common/cardDeposit", "获取押金数据失败");
  },
  //获取水卡类型
  getCardType() {
    return this.fetch("Partner/WaterCard/getCarType", "获取水卡类型", {
      type: 2,
      is_apply: 1
    });
  },
  //获取相关证件
  getCredentialType() {
    return this.fetch("Partner/WaterCard/getCredentialType", "获取证明材料配置失败");
  },

  //获取充值金额配置
  getSpecialCardRechargeConfig() {
    return this.fetch("Partner/WaterCard/getSpecialCardRechargeConfig", "获取充值金额配置失败")
  },


  typeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value
    })
  },

  // 性别
  // sexChange: function (e) {
  //   this.setData({
  //     sexIndex: e.detail.value
  //   })
  // },
  // 审核类型
  auditChange: function (e) {
    this.setData({
      auditIndex: e.detail.value
    })
  },

  // 充值金额
  rechargeChange: function (e) {
    this.setData({
      rechargeIndex: e.detail.value
    })
  },
  // 所属园区
  communityChange: function (e) {
    let index = e.detail.value;
    let community = this.data.communityList[index];
    let address = [...new Set([community.province_name, community.city_name, community.area_name])];
    console.log(address, "area_name")
    this.setData({
      communityIndex: index,
      address: `${address.join("")}${community.address}`
    })
  },

  // 相关证件
  certificatesChange: function (e) {
    this.setData({
      certificatesIndex: e.detail.value
    })
  },

  // 证件照片
  uploadImg: function () {
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        wx.showLoading({
          title: '资源上传中',
        })
        that.setData({
          isUpload: true
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          that.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = JSON.parse(JSON.stringify(that.data.all_url_arr));
          let url_arrs = JSON.parse(JSON.stringify(that.data.url_arr));
          url_arrs.push(source.data.url);
          all_url_arrs.push(source.data.all_url);
          if (i == len) {
            wx.hideLoading();
            that.setData({
              isUpload: false
            })
          }
          that.setData({
            all_url_arr: all_url_arrs,
            url_arr: url_arrs
          })
        } else {
          app.showToast("上传图片失败");
          that.setData({
            isUpload: false
          })
        }
        //do something
      }
    })
  },
  //删除图片
  deleteImg(e) {
    var that = this;
    let index = e.currentTarget.dataset.index,
      all_url_arr = that.data.all_url_arr,
      url_arr = that.data.url_arr;

    all_url_arr.splice(index, 1);
    url_arr.splice(index, 1);
    that.setData({
      all_url_arr: all_url_arr,
      url_arr: url_arr
    })
  },
  //押金选择
  depositChange(e) {
    this.setData({
      depositIndex: e.detail.value
    })
  },
  //图片预览
  lookImg(e) {
    let url0 = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: this.data.all_url_arr,
      current: url0
    })
  },
  // 确认
  formSubmit: function (e) {
    var that = this;
    let info = e.detail.value;
    let full_name = info.username,
      // sex = parseInt(info.sex) + 1,
      audit_type = parseInt(info.audit_type) + 1,
      tel = info.phonenum,
      paper_type = that.data.certificatesList[info.certificates].id,
      IDcard = info.idcard,
      sn = info.cardnum,
      card_type = '',
      village_name = "",
      address = info.address,
      card_price = that.data.rechargeList[info.recharge],
      audit_data = that.data.url_arr,
      deposit = that.data.deposit[that.data.depositIndex];
    if (info.type === '') {
      app.showToast('请选择水卡类型');
      return false;
    } else {
      card_type = that.data.typeList[info.type].id;
    }
    if (info.community === '') {
      app.showToast('请选择园区');
      return false;
    } else {
      village_name = that.data.communityList[info.community].village_name;
    }
    if (full_name == '') {
      app.showToast('请输入用户姓名');
      return false;
    }
    if (tel == '') {
      app.showToast('请输入用户手机号码');
      return false;
    }
    if (address == '') {
      app.showToast('请输入详细地址');
      return false;
    }
    if (that.data.depositIndex === "") {
      app.showToast("请选择押金");
      return false;
    }
    if (sn == '') {
      app.showToast('请输入水卡卡号');
      return false;
    }
    if (IDcard == '') {
      app.showToast('请输入请输入证件号码');
      return false;
    }
    if (audit_data.length == 0) {
      app.showToast("请上传证件照片");
      return;
    }
    let data = {
      full_name: full_name,
      // sex: sex,
      tel: tel,
      card_class: 2,
      card_type: card_type,
      paper_type: paper_type,
      IDcard: IDcard,
      sn: sn,
      address: address,
      village_name: village_name,
      card_price: card_price,
      deposit: deposit,
      audit_data: audit_data,
      audit_type: audit_type
    }
    let url = "";
    if (that.data.pageType == 0) {
      url = "Partner/WaterCard/auditSpecialCard";
    } else {
      url = "Partner/WaterCard/editSpecialApplication"
      data.id = that.data.id;
    }
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url,
      data,
      success: function (res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          if (that.data.pageType == 0) {
            setTimeout(() => {
              wx.redirectTo({
                url: '../specialApplyList/specialApplyList',
              })
            }, 1500)
          } else {
            that.navigateBackAndUpdateList();
          }
        } else {
          app.showToast(res.data.message);
        }
      },
      error: function () {
        wx.hideLoading()
        app.showToast("网络错误,请稍后重试", "none", 2000, function () {});
      }
    })
  },



  //获取水卡信息
  getIngo(id) {
    var that = this;
    app.ajax({
      url: 'Partner/WaterCard/getWaterCardAudit',
      method: "POST",
      data: {
        id: id
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 1000) {
          let info = res.data.data;

          let typeIndex = that.data.typeList.findIndex(current => info.card_type_number == current.id);
          let rechargeIndex = that.data.rechargeList.findIndex(current => parseInt(info.recharge_money) == current);
          let depositIndex = that.data.deposit.findIndex(current => parseInt(info.card_deposit) == current);
          let certificatesIndex = that.data.certificatesList.findIndex(current => parseInt(info.paper_type_number) == current.id);
          let communityIndex = that.data.communityList.findIndex(current => current.id == info.village_id)
          that.setData({
            communityIndex,
            typeIndex,
            username: info.full_name,
            // sexIndex: parseInt(info.sex_number) - 1,
            auditIndex: parseInt(info.audit_type) - 1,
            phonenum: info.tel,
            address: info.address,
            rechargeIndex: rechargeIndex,
            depositIndex: depositIndex,
            cardnum: info.card_number,
            certificatesIndex: certificatesIndex,
            idcard: info.IDcard,
            all_url_arr: info.audit_data,
            url_arr: info.audit_data,
          })
        } else {
          app.showToast("网络错误,请稍后重试", "none", 2000, function () {});
        }
      }
    })
  },

  navigateBackAndUpdateList() {
    const pages = getCurrentPages();
    if (pages.length >= 2) {
      const listPage = pages[pages.length - 2];
      listPage.setData({
        page: 1,
        applyList: [],
      })
      listPage.getApplyList();
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },
})